<?php
namespace control;
/*
*计时计件汇总类
*/

class pieceStatisticsClass extends adIndexClass
{
    private const page = 'pieceStatistics'; # 权限
    private const table = 'piece_statistics'; # 数据表
    private const title = '计时计件汇总';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'settedSearch':
                $tr = [
                    'teamName'          => [
                        'name'  => "班组",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'stName'  => [
                        'name'  => '员工',
                        'width' => 300,
                    ],
                    'hourMoney'         => [
                        'name'  => '计时工资',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'pieceMoney'          => [
                        'name'  => '计件工资',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'money'          => [
                        'name'  => '工资合计',
                        'width' => 300,
                        'sort' => 1,
                    ]
                ];
                break;
            case 'settingSearch':
                $tr = [
                    'team'          => [
                        'name'  => "班组",
                        'width' => 300,
                    ],
                    'staff'  => [
                        'name'  => '员工',
                        'width' => 300,
                    ],
                    'timeMoney'         => [
                        'name'  => '计时工资',
                        'width' => 300,
                    ],
                    'pieceMoney'          => [
                        'name'  => '计件工资',
                        'width' => 300,
                    ],
                    'total'          => [
                        'name'  => '工资合计',
                        'width' => 300,
                    ]
                ];
                break;
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编号",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'month'  => [
                        'name'  => '月份',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'stid'         => [
                        'name'  => '申请人',
                        'width' => 300,
                    ],
                    'time'          => [
                        'name'  => '单据日期',
                        'width' => 300,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 300,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号"   => text(["name" => "orderNo"]),
                    "月份"   => text(["name" => "month", 'laydate' => ['type' => 'month']]),
                    "申请人部门"   => text(["name" => "deptName"]),
                ],
                [
                    "申请人"   => selectMultiple(array("name" => "stid", "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid', 'class' => 'width200')),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => ['草稿', '审核中', '已通过']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表页-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{id:'" . suiji() . "'})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function homeSearch(): bool|string
    {
        $like = [
            "orderNo" => $this->post('orderNo'),
            "deptName" => $this->post('deptName'),
        ];
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),
            "month" => $this->post('month'),
            "state" => $this->post('state'),
            'coid' => self::$coid,
        );
        $and = '';
        if ($this->post('createTime')) {
            //单据日期
            $and .= self::timeComparison($this->post('createTime'));
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
//                'edit' => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'".$array['id']."'})"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case 'time':
                        $row[] = date('Y-m-d', strtotime($array['time']));
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;

        return json_encode($json, 320);
    }

    /**
     * 编辑
     */
    public function edit(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "月份：" => text(array('name' => 'month', 'laydate' => ['type' => 'month'], 'value' => date('Y-m'))),
            ),
        )));
        //返回
        return $this->layer(array("title" => "编辑", "height" => 200, "width" => 600, "html" => $html));
    }


    /*异步处理*/
    public function editEdit(): bool|string
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'month' => $this->post('month'),
        ];
        $annotation = [
            'month' => '月份',
        ];
        $rules = [
            'month' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(['table' => self::table, 'where' => " month = '$field[month]' and coid ='" . self::$coid . "' and id !='$id'"]) > 0) {
            $json['warn'] = "已存在此月份的" . self::title;
        } elseif (!empty($info['id'])) {
            $json['warn'] = "已存在的汇总不可修改";
        } else {
            $department = query('department', "id = '" . $this->controlJob['departmentId'] . "'");
            $userNo = codeTemplateClass::generateCode(self::page,[
                'prefix' => 'JSJJ' . date('Ymd'),
                'table' => self::table,
                'field' => 'orderNo',
                'where' => " and coid = '" . self::$coid . "'",
            ],$field);
            $field = array_merge($field, ["id" => $id, 'orderNo' => $userNo, 'deptName' => $department['name'], 'coid' => self::$coid, 'stid' => self::$stid, 'state' => '草稿']);
            $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
        }

        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个" . self::title . ",月份：" . $field['month'] . ",ID：" . $id;
            $this->logText(["type" => self::page, "text" => $text]);
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=detail&id=' . $id;
        }
        //返回
        resp:
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '计时计件',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];

        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    /**
     * 明细
     * @return bool|string
     */
    public function detail(): bool|string
    {
        $info = query(self::table, " id = '" . $this->get('id') . "' ");
        if (!$this->power(self::page, "see")) {
            $html = "你没有查看计时计件汇总的权限";
        } elseif (empty($info['id'])) {
            $html = "未找到此计时计件汇总";
        } else {
            $data = [
                "id" => $info['id'],
                'menu' => [
                    "detail" => "基本信息",
                    'setting' => '待计提',
                    'setted' => '已计提',
                ]
            ];
            //按钮
            $button = [];
            //审核按钮
            $button = array_merge($button, $this->auditButton($info));
            $audit = query('audit', " targetId = '$info[id]'");
            if ($info['state'] == '草稿') {
                if ($this->power(self::page, 'edit')) {
                    $button[] = [
                        "name" => "上传附件",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "attachFile",
                        "post" => ["id" => $info['id']],
                    ];
                }
                if ($this->power(self::page, 'del')) {
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }


            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                [
                    array(
                        "单据编号" => $info['orderNo'],
                        "月份" => $info['month'],
                        "申请人部门" => $info['deptName'],
                        "申请人" => self::findStaff($info['stid']),
                    ),
                    array(
                        "创建时间" => $info['time'],
                        "提交时间" => self::null($audit['commitTime']),
                        "状态" => $info['state'],
                    ),
                ],
                '附件' => array(
                    array(
                        fileUploadClass::showFile($info['id'], '计时计件汇总')
                    )
                ),
                '流程' => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id'])
                    )
                ),
            ]);
            $html = $this->tab($data) . $this->homeJs();
        }

        //返回
        return $html;
    }

    public function homeJs()
    {
        return <<<eof
<script>
function get_list_box(formName) {
    let arr = [];
    $("[name='" + formName + "'] input[type=checkbox]:checked").each(function () {
        if ($(this).val() && $(this).val() !== 'on') {
            arr.push($(this).val());
        }
    });
    if (arr.length > 0) {
        var vals = arr.join(",");
       window.open(root+'control/adIndex.html?cla=pieceStatistics&fun=printEdit&listId='+vals)
    } else {
        msg('请选择需要数据');
    }
}
</script>
eof;

    }

    public function attachFile()
    {
        $id = $this->post('id');
        if (empty($id)) {
            $html = "未找到此汇总";
        } else {
            //生成表单
            $html = $this->layerEdit(array("table" => array(
                array(
                    "附件：" => fileUploadClass::addFileComponent($id, '计时计件汇总', self::page, 'pieceStatisticsAttachFileForm'),
                ),
            )));
        }
        //返回
        return $this->layer(array("title" => "编辑", "height" => 300, "width" => 800, "html" => $html));
    }

    public function attachFileEdit()
    {
        $id = $this->post('id');
        $fileIdArr = $this->post('fileId');
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($fileIdArr)) {
            $json['warn'] = "未找到上传的附件";
        } elseif (empty($info['id'])) {
            $json['warn'] = "未找到此汇总表";
        } else {
            $json['warn'] = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                //添加日志
                $text = $this->control['name'] . "上传了" . self::title . "的附件,月份：" . $info['month'] . ",ID：" . $id;
                $this->logText(["type" => self::page, "text" => $text]);
                //提示
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=detail&id=' . $id;
            } else {
                $json['warn'] = '上传失败';
            }
        }


        //返回
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate(): bool|string
    {
        $act = $this->post('act') ?? '';
        $pwd = $append = false; // 需要密码
        switch ($act) {
            case 'delContact':
                $act = 'staffDel';
                $msg = '删除联系人';
                $title = self::page . 'Contact';
                $function = 'deleteContact';
                $append = [hidden(['name' => 'orderId', 'value' => $this->post['orderId']])];
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'append' => $append,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "已确认状态，暂不能删除";
                } else {
                    $result = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($result['array'] as $file) {
                        fileDelete($file['src']);
                    }
                    //删除附件
                    delete(array("table" => "file", "where" => " targetId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::table . '_detail', "where" => " orderId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function settedOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "班组" => selectMultiple(array("name" => "teamId", "table" => "team", 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name', 'sqlId' => 'id', 'class' => 'width200')),
                    "员工"   => selectMultiple(array("name" => "stid", "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid', 'class' => 'width200')).
                        hidden(array('name' => 'id', 'value' => $this->get('id'))),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 已计提
     */
    public function setted(): bool|string
    {
        $html = $this->settedOptions(false);
        //控件
        $button = '';
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',exportFun:'exportData2'})\">导出</span>";
        }
        if ($this->power(self::page, "print")) {
            $button .= "<span onclick=\"window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printSetting')\" class='spanButton'>打印</span>\n";
        }
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    /**
     * 已计提
     * @return bool|string
     */
    public function settedSearch(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '$id'");
        //like查询数组
        $like = array();
        //全等查询数组
        $equal = array(
            'teamId' => $this->post('teamId'),
            'stid' => $this->post('stid'),
        );
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . " and orderId = '$id'";
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $page = $this->page([
            "table" => 'piece_statistics_detail',
            "where" => $where,
            'order' => $orderBy['orderBy']
        ]);
        $_SESSION[self::page]['sql2'] = $page['fullSql'];
        $_SESSION[self::page]['id'] = $info['id'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array($this->checkAll("settedForm", "listId"));
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = [
                "box" => [
                    "name" => "listId",
                    "value" => $array['id']
                ],
            ];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = '';
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        //控件
        $json['html'] = $page['hint'] . $button . "<form name='settedForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function settingOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "班组" => selectMultiple(array("name" => "teamId", "table" => "team", 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name', 'sqlId' => 'id', 'class' => 'width200')),
                    "员工"   => selectMultiple(array("name" => "stid", "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid', "class" => "width200")).
                        hidden(array('name' => 'id', 'value' => $this->get('id'))),
                ]
            ]
        ]);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 待计提
     */
    public function setting(): bool|string
    {
        $html = $this->settingOptions(false);
        //控件
        $button = '';
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "print")) {
            $button .= "<span onclick=\"window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage')\" class='spanButton'>打印</span>\n";
        }
        if ($this->power(self::page, "pay")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'pay', {id:'" . $this->get('id') . "'})\">批量计提</span>\n";
        }
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    /**
     * 待计提
     * @return bool|string
     */
    public function settingSearch(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '$id'");
        //查询结果
        $whereOne = "1=1 and b.classify = '工序报工' and b.state = '已确认' and b.coid = '" . self::$coid . "' and date_format(teamNo,'%Y-%m') = '$info[month]' and main.stid not in (select staffId from piece_statistics_detail where orderId = '$id')";
        $whereTwo = "1=1 and coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m') = '$info[month]' and staffId not in (select staffId from piece_statistics_detail where orderId = '$id')";

        if ($this->post('teamId')) {
            $whereOne .= " and b.teamId = '" . $this->post('teamId') . "'";
            $whereTwo .= " and teamId = '" . $this->post('teamId') . "'";
        }
        if ($this->post('stid')) {
            $whereOne .= " and a.stid = '" . $this->post('stid') . "'";
            $whereTwo .= " and staffId = '" . $this->post('stid') . "'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'teamId',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $page = $this->page([
            "table" => "process_report_staff as main join process_report as b on main.orderId = b.id where  {$whereOne} UNION select distinct staffId,teamId from timing_report",
            'field' => 'distinct main.stid as staffId,b.teamId as teamId',
            "where" => $whereTwo,
            'pageNum' => 50,
            'union' => "select ifnull(count(distinct main.stid),0) as num from process_report_staff as main join process_report as b on main.orderId = b.id where {$whereOne} UNION select ifnull(count(distinct staffId),0) as num from timing_report where {$whereTwo}",
            "order" => $orderBy['orderBy']
        ]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        $_SESSION[self::page]['id'] = $info['id'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array($this->checkAll("settingForm", "listId"));
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = [
                "box" => [
                    "name" => "listId",
                    "value" => $array['staffId']
                ],
            ];
            $liButton[] = $this->dominate($dominate);
            $timeMoney = $this->timeMoney($info['month'], $array['staffId'], $array['teamId']);
            $pieceMoney = $this->pieceMoney($info['month'], $array['staffId'], $array['teamId']);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "team":
                        $team = query('team', "id = '$array[teamId]'");
                        $row[] = $team['name'];
                        break;
                    case "staff":
                        $staff = query('staff', "stid = '$array[staffId]'");
                        $row[] = $staff['name'];
                        break;
                    case "timeMoney":
                        $row[] = $timeMoney;
                        break;
                    case "pieceMoney":
                        $row[] = $pieceMoney;
                        break;
                    case "total":
                        $row[] = $timeMoney + $pieceMoney;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = '';
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        //控件
        $json['html'] = $page['hint'] . $button . "<form name='settingForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 拨付
     * @return bool|string
     */
    public function pay()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                '提示' => " 是否确定拨付所选择的记录？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "拨付", "height" => 160, "width" => 600, "html" => $html, 'formTwo' => 'settingForm'));
    }

    /**
     * 拨付编辑
     * @return bool|string
     */
    public function payEdit()
    {
        $listId = $this->post('listId');
        $id = $this->post('id');
        $info = query(self::table, "id = '$id'");
        if (!$this->power(self::page, "pay")) {
            $json['warn'] = "你没有" . self::title . "的拨付权限";
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = "请选择数据";
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此汇总表';
        } elseif ($info['state'] != '已通过') {
            $json['warn'] = '此记录还未审核通过';
        } else {
            $x = 0;
            $whereOne = "1=1 and b.classify = '工序报工' and b.state = '已确认' and b.coid = '" . self::$coid . "' and date_format(teamNo,'%Y-%m') = '$info[month]' and main.stid in ('" . implode("','", $listId) . "')";
            $whereTwo = "1=1 and coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m') = '$info[month]' and staffId in ('" . implode("','", $listId) . "')";
            $all = find([
                "table" => "process_report_staff as main join process_report as b on main.orderId = b.id where  {$whereOne} UNION select distinct staffId,teamId from timing_report",
                'field' => 'distinct main.stid as staffId,b.teamId as teamId',
                "where" => $whereTwo,
                'pageNum' => 50,
                'union' => "select ifnull(count(distinct main.stid),0) as num from process_report_staff as main join process_report as b on main.orderId = b.id where {$whereOne} UNION select ifnull(count(distinct staffId),0) as num from timing_report where {$whereTwo}",
            ]);
            foreach ($all['array'] as $array) {
                $mx = query('piece_statistics_detail', " orderId = '$id' and teamId = '$array[teamId]' and staffId = '$array[staffId]'");
                $team = query('team', "id = '$array[teamId]'");
                $staff = query('staff', "stid = '$array[staffId]'");
                if (!$mx['id']) {
                    $timeMoney = $this->timeMoney($info['month'], $array['staffId'], $array['teamId']);
                    $pieceMoney = $this->pieceMoney($info['month'], $array['staffId'], $array['teamId']);
                    $suiji = suiji();
                    $warn = insert(array(
                        "table" => 'piece_statistics_detail',
                        "field" => [
                            'id' => $suiji,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'teamId' => $array['teamId'],
                            'staffId' => $array['staffId'],
                            'teamName' => $team['name'],
                            'stName' => $staff['name'],
                            'hourMoney' => $timeMoney,
                            'pieceMoney' => $pieceMoney,
                            'money' => $timeMoney + $pieceMoney,
                            'checkId' => self::$stid,
                            'confirmTime' => $this->time,
                        ],
                        'where' => " id = '$id'"
                    ));
                    if ($warn == '新增成功') {
                        $x++;
                        //添加日志
                        $text = $this->control['name'] . "拨付了班组【{$team['name']}】,员工【{$staff['name']}】-【{$info['month']}】月份的工资，id：【" . $suiji . '】';
                        $this->logText(["type" => self::page, "text" => $text]);
                    }
                } else {
                    $text = $this->control['name'] . "拨付班组【{$team['name']}】,员工【{$staff['name']}】-【{$info['month']}】月份的工资失败：不是已通过状态或已拨付";
                    $this->logText(["type" => self::page, "text" => $text]);
                }
            }
            //返回
            $_SESSION['warn'] = "成功拨付了{$x}条数据";
            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=detail&menu=setting&id=' . $info['id'];
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 计件工资
     * @param $month
     * @param $staffId
     * @param $teamId
     * @return float|int
     */
    public function pieceMoney($month, $staffId, $teamId): float|int
    {
        $personMoney = 0;
        $pieceCountClass = new pieceCountClass();
        $all = find(array("table" => "process_report_staff as a join process_report as b on a.orderId = b.id",
            'field' => "b.*,a.stid as teamStid", "where" => "date_format(teamNo,'%Y-%m') = '$month' and a.stid = '$staffId' and b.teamId = '$teamId' and b.state = '已确认' and b.coid = '" . self::$coid . "' and b.classify = '工序报工'"));
        foreach ($all['array'] as $array) {
            $material = query('material', "id = '$array[materialId]'");
            if ($array['sourceTable'] == 'machining_send_order'){
                $machining_send_order= query('machining_send_order', "id = '$array[sendId]'");
                $routMx = query('routing_detail', "id = '$machining_send_order[routingMxId]'");
            }else{
                $machining_card_detail= query('machining_card_detail', "id = '$array[sendId]'");
                $routMx = query('routing_detail', "id = '$machining_card_detail[routingMxId]'");
            }
            $array['yield'] = machiningOrderClass::material_num_change($array['materialId'], $array['unit'], $material['unit'], $array['yield']);
            $routMx['price'] = $routMx['price'] ?: 0;
            $salary = round((float)$routMx['price'] * $array['yield'], 2);
            if ($array['valuationType'] == '个人计件') {
                $personMoney = $salary;
            } else {
                $team_detail = query('team_detail', "orderId = '$array[teamId]' and stid = '$array[teamStid]'");
                $team_detail['rate'] = $team_detail['rate'] ?: 0;
                //当前班组人员考勤
                $workshop_clock_detail = find(array('table' => 'workshop_clock as a join workshop_clock_detail as b on a.id = b.orderId', 'single' => "a.state !='草稿' and a.teamId like '%$array[teamId]%' and b.stid = '$array[teamStid]' and b.recordDate = '$array[teamNo]'", 'field' => "b.hour"));
                $workshop_clock_detail['hour'] = $workshop_clock_detail['hour'] ?? 0;
                $rateSum = $pieceCountClass->caculate($array['teamId'], $array['teamNo']);
                //公式  计件工资*（个人计件系数*个人考勤）/(班组中每个人的(个人考勤*个人系数)之和)
                $personMoney += $rateSum > 0 ? round($salary * ($team_detail['rate'] * $workshop_clock_detail['hour'] / $rateSum), 2) : 0;
            }
        }
        return $personMoney;
    }

    /**
     * 计时工资
     * @param $month
     * @param $staffId
     * @param $teamId
     * @return float
     */
    public function timeMoney($month, $staffId, $teamId): float
    {
        $hour = find(array('table' => 'timing_report', 'where' => "date_format(recordDate,'%Y-%m') = '$month' and teamId = '$teamId' and staffId = '$staffId' and coid = '" . self::$coid . "'", 'sum' => "hour"));
        $teamMx = query('team_detail', "orderId = '$teamId' and stid = '$staffId'");
        $teamMx['price']=$teamMx['price']?:0;
        return round($hour * (float)$teamMx['price'], 2);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $info = query(self::table, "id = '" . $_SESSION[self::page]['id'] . "'");
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } elseif (empty($info['id'])) {
            $_SESSION['warn'] = '未找到此汇总表';
        } else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            $sql   = $_SESSION[self::page]['sql'];
            $result   = sqlFind($sql);
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $team = query('team', "id = '$array[teamId]'");
                $staff = query('staff', "stid = '$array[staffId]'");
                $timeMoney = $this->timeMoney($info['month'], $array['staffId'], $array['teamId']);
                $pieceMoney = $this->pieceMoney($info['month'], $array['staffId'], $array['teamId']);
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '班组'=>$team['name'],
                            '员工'=>$staff['name'],
                            '计时工资'=>$timeMoney,
                            '计件工资'=>$pieceMoney,
                            '工资合计'=>$timeMoney + $pieceMoney,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了计时计件汇总待计提";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "计时计件汇总待计提.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    public function exportData2()
    {
        $info = query(self::table, "id = '" . $_SESSION[self::page]['id'] . "'");
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } elseif (empty($info['id'])) {
            $_SESSION['warn'] = '未找到此汇总表';
        } else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => 'piece_statistics_detail',
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql2'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '班组'=>$array['teamName'],
                            '员工'=>$array['stName'],
                            '计时工资'=>$array['hourMoney'],
                            '计件工资'=>$array['pieceMoney'],
                            '工资合计'=>$array['money'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了计时计件汇总已计提";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "计时计件汇总已计提.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 样式
     * @return string
     */
    public function style(): string
    {
        return <<<eof
<style>
.stateBlock{margin-top: 0}
.stateBlock ul li{padding: 2px 10px}
.footer-ul-parent{float: right;margin-right: 10px}
.table-top-title{height: 30px;line-height: 30px;font-size: 14px;margin-top: 20px;}
.table-top-title>ul{display: flex;flex-direction: row;padding: 2px 5px}
.table-top-title>ul>li{flex:1}
</style>
eof;

    }
    public function printSetting()
    {
        $id = $_SESSION[self::page]['id'];
        $sql = $_SESSION[self::page]['sql2'];
        $result['array'] = sqlFind($sql);
        $info = query(self::table, " id = '$id'");
        $company = query('company', "coid = '" . self::$coid . "'");//公司名称
        $goodsHtml = '';
        $totalMoney = 0;
        foreach ($result['array'] as $array) {
            $goodsHtml .= "
                             <tr class='have_border'>
                               <td>{$array['teamName']}</td>
                               <td>{$array['stName']}</td>
                               <td>{$array['hourMoney']}</td>
                               <td>{$array['pieceMoney']}</td>
                               <td>{$array['money']}</td>
                             </tr>
                            ";
        }
        $divHtml = "
                 <div>
                      <div class='printTitle' style='font-weight: bold'>{$company['name']}</div>
                      <div class='printSubTitle'>{$info['month']}月已计提工资</div>
                 </div>
                 <div class='table-top-title'></div>
              <table class='printTable'  data-op-type='block-box'>
                <tbody class='nop-fill-box'>
               <tr class='have_border'>
                   <td>班组</td>
                   <td>员工</td>
                   <td>计时工资</td>
                   <td>计件工资</td>
                   <td>工资合计</td>
                </tr>
                {$goodsHtml}
                 <tr class='have_border'>
                    <td>合计</td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td>{$totalMoney}</td>
                </tr>

                 <tr class='have_border'>
                    <td colspan='13'>
                         <div>
                               <div class='footer-ul-parent'>
                               <ul class='footer-ul'>
                                   <li>打印时间：" . date('Y/m/d H:i') . "</li>
                                   <li>制单人：" . self::findStaff($info['stid']) . "</li>
                               </ul>
                               </div>
                         </div>
                    </td>
                </tr>
               </tbody>
              </table>
            ";
        $html = <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       {$divHtml}
                    </div>
                  <style>
                  .footer-ul-parent{float: right;margin-right: 10px}
                  .footer-ul li{margin-top: 10px}
                  .table-top-title{
                    height: 30px;
                    line-height: 30px;
                    font-size: 14px;
                    margin-top: 20px;
                  }
                  .table-top-title>ul>li{float: left;width: 250px;}
</style>
eof;
        $print = new printClass();

        return $print->showPrint($html, 'landscape');
    }
    public function printPage()
    {
        $id = $_SESSION[self::page]['id'];
        $sql = $_SESSION[self::page]['sql'];
        $result['array'] = sqlFind($sql);
        $info = query(self::table, " id = '$id'");
        $company = query('company', "coid = '" . self::$coid . "'");//公司名称
        $goodsHtml = '';
        $totalMoney = 0;
        foreach ($result['array'] as $array) {
            $team = query('team', "id = '$array[teamId]'");
            $staff = query('staff', "stid = '$array[staffId]'");
            $timeMoney = $this->timeMoney($info['month'], $array['staffId'], $array['teamId']);
            $pieceMoney = $this->pieceMoney($info['month'], $array['staffId'], $array['teamId']);
            $money = $timeMoney + $pieceMoney;
            $totalMoney += $money;
            $goodsHtml .= "
                             <tr class='have_border'>
                               <td>{$team['name']}</td>
                               <td>{$staff['name']}</td>
                               <td>{$timeMoney}</td>
                               <td>{$pieceMoney}</td>
                               <td>{$money}</td>
                             </tr>
                            ";
        }
        $divHtml = "
                 <div>
                      <div class='printTitle' style='font-weight: bold'>{$company['name']}</div>
                      <div class='printSubTitle'>{$info['month']}月待计提工资</div>
                 </div>
                 <div class='table-top-title'></div>
              <table class='printTable'  data-op-type='block-box'>
                <tbody class='nop-fill-box'>
               <tr class='have_border'>
                   <td>班组</td>
                   <td>员工</td>
                   <td>计时工资</td>
                   <td>计件工资</td>
                   <td>工资合计</td>
                </tr>
                {$goodsHtml}
                 <tr class='have_border'>
                    <td>合计</td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td>{$totalMoney}</td>
                   
                </tr>

                 <tr class='have_border'>
                    <td colspan='13'>
                         <div>
                               <div class='footer-ul-parent'>
                               <ul class='footer-ul'>
                                   <li>打印时间：" . date('Y/m/d H:i') . "</li>
                                   <li>制单人：" . self::findStaff($info['stid']) . "</li>
                               </ul>
                               </div>
                         </div>
                    </td>
                </tr>
               </tbody>
              </table>
            ";
        $html = <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       {$divHtml}
                    </div>
                  <style>
                  .footer-ul-parent{float: right;margin-right: 10px}
                  .footer-ul li{margin-top: 10px}
                  .table-top-title{
                    height: 30px;
                    line-height: 30px;
                    font-size: 14px;
                    margin-top: 20px;
                  }
                  .table-top-title>ul>li{float: left;width: 250px;}
</style>
eof;
        $print = new printClass();

        return $print->showPrint($html, 'landscape');
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'班组',
                    'aliasName'=>'班组',
                ],
                [
                    'columnName'=>'员工',
                    'aliasName'=>'员工',
                ],
                [
                    'columnName'=>'计时工资',
                    'aliasName'=>'计时工资',
                ],
                [
                    'columnName'=>'计件工资',
                    'aliasName'=>'计件工资',
                ],
                [
                    'columnName'=>'工资合计',
                    'aliasName'=>'工资合计',
                ],
            ]
        };
    }
}
